//
//  NetworkTools.swift
//  
//
//  Created by ZhuDong on 16/5/22.
//
//

import UIKit
import AFNetworking

enum Methods: Int{
    case GET
    case POST
}
struct API{
    static let hostName = "https://api.weibo.com/"
    static let loadAccessToken = "oauth2/access_token"
    static let loadUserInfo = "2/users/show.json"
    static let loadHomeInfo = "2/statuses/home_timeline.json"
    static let sendStatus = "2/statuses/update.json"
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
}
class NetworkTools: AFHTTPSessionManager {
    static let tools: NetworkTools = {
        let baseUrl = NSURL(string: API.hostName)
       let t = NetworkTools(baseURL: baseUrl)
    t.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        t.responseSerializer.acceptableContentTypes?.insert("text/plain")
       
        return t
    }()

    func request(requestMethod: Methods,URLString: String, parameters: AnyObject?,finish: ((responseObject: AnyObject?,error: NSError?)->(Void))){
        let success = { (task: NSURLSessionDataTask?, responseObject: AnyObject?) -> Void in
            //执行请求成功的回调
            finish(responseObject: responseObject, error: nil)
        }
        let failure = { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
            //执行请求成功的回调
            finish(responseObject: nil, error: error)
        }
        if requestMethod == Methods.GET {
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

        }else{
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
 
        }
    }
}
extension NetworkTools{
    //获取token值方法
    func loadAccessToken(code: String,finish:((responseObject: AnyObject?,error: NSError?)->(Void))){
        let parameters: [String : AnyObject] = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let urlStr = API.loadAccessToken
        request(.POST, URLString: urlStr, parameters: parameters, finish: finish)
    }
    //获取用户信息方法
    private func loadUserInfo(response: AnyObject?,finish:((responseObject: AnyObject?,error: NSError?)->(Void))){
        
        guard let tokenInfo = response as? [String:AnyObject] else{
            print("请求错误2")
            return
        }
        let token = tokenInfo["access_token"]!
        let uid = tokenInfo["uid"]!
        let urlStr = API.loadUserInfo
        let parameters = ["access_token":token,"uid":uid]
        request(.GET, URLString: urlStr, parameters: parameters, finish: finish)
    }
}
extension NetworkTools{
    func loadHomePageData(since_id: Int64,max_id : Int64, finish:((responseObject: AnyObject?,error: NSError?)->(Void))){
        guard let token = HMUserAccountViewModel.shareAccountViewModel.userAccount?.access_token else{
            print("用户信息存储错误")
            return
        }
        var tokenParameter = ["access_token":token]
        print(tokenParameter)
        if since_id > 0 {
            tokenParameter["since_id"] = "\(since_id)"
        }
        if max_id > 0{
            tokenParameter["max_id"] = "\(max_id)"
        }
        let urlStr = API.loadHomeInfo
        self.request(.GET, URLString: urlStr, parameters: tokenParameter, finish: finish)
    }
}
extension NetworkTools{
    func sendStatus(stauts: String, images: [UIImage],finish:((responseObject: AnyObject?,error: NSError?)->(Void))){
        guard let token = HMUserAccountViewModel.shareAccountViewModel.userAccount?.access_token else{
            return
        }
        let paras = ["access_token":token,"status":stauts]
        if images.count > 0 {
            POST(API.sendImageStatus, parameters: paras, constructingBodyWithBlock: { (formData:AFMultipartFormData) in
                /*
                for image in images{
                    let data = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(data, name: "pic", fileName: "dsfs", mimeType: "application/octet-stream")
                }
                */
                for image in images {
                    let imageData = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "ococooc", mimeType: "application/octet-stream")
                }
                }, progress: nil, success: { (dataTask: NSURLSessionDataTask,responseObject: AnyObject?) in
                    finish(responseObject: responseObject, error: nil)
                }, failure: { (dataTask: NSURLSessionDataTask?,error: NSError) in
                    finish(responseObject: nil, error: error)
            })
        }else{
            request(.POST, URLString: API.sendStatus, parameters: paras, finish: finish)
        }
    }
}